package com.fyt.service.serviceImp;

import com.fyt.result.R;
import com.fyt.service.DiscoveryService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author ：fyt
 * @Date: 2024/4/13 18:17
 */
@Service
public class DiscoverySDKServiceImpl implements DiscoveryService {

    @Autowired
    private Environment environment;
    @Value("${serverAddr.ip}")
    private String nacosIp;
    @Value("${serverAddr.port}")
    private Integer nacosPort;
    @Value("${localAddr.serviceName}")
    private String serviceName;
    private static final String SERVER_PORT = "server.port";
    private static final String COLON = ":";

    @Override
    public R registerNacosInstance() {
        // 初始化NamingService对象
        NamingService naming = null;
        try {
            // 获取nacos服务器
            String saveAddr = nacosIp + COLON + nacosPort;
            naming = NamingFactory.createNamingService(saveAddr);
            // 初始化服务实例
            Instance instance = new Instance();
            String localHost = InetAddress.getLocalHost().getHostAddress();
            instance.setIp(localHost);
            instance.setPort(Integer.parseInt(environment.getProperty(SERVER_PORT)));
            // 注册服务
            naming.registerInstance(serviceName, instance);
            return R.Success();
        } catch (NacosException e) {
            e.printStackTrace();
            return R.Failed("服务注册失败");
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return R.Failed("获取本机ip失败");
        }
    }
}
